package com.wlt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlt.mapper.BrandMapper;
import com.wlt.pojo.Brand;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service                         // 普通的service只是加到shopping-goods-service容器中
@DubboService(timeout = 10000)   // 因此要用DubboService，它会注册到nacos中，支持dubbo的服务调用
@Transactional                   // 添加事务，因为服务层的注解是不可分割的
public class BrandServiceImpl implements BrandService
{
    @Autowired
    private BrandMapper brandMapper;
    
    /**
     * 根据ID查询品牌
     *
     * @param id
     * @return
     */
    @Override
    public Brand findById (Long id)
    {
//        if(id == 0)
//        {
//            // 模拟系统异常
//            int i = 1 / 0;
//        }
//        else if(id == -1)
//        {
//            // 模拟业务异常
//            throw new BusException(CodeEnum.PARAMETER_ERROR);
//        }
        
        return brandMapper.selectById(id);
    }
    
    @Override
    public List<Brand> findAll ()
    {
        return brandMapper.selectList(null);
    }
    
    @Override
    public void add (Brand brand)
    {
        brandMapper.insert(brand);
    }
    
    @Override
    public void update (Brand brand)
    {
        brandMapper.updateById(brand);
    }
    
    @Override
    public void delete (Long id)
    {
        brandMapper.deleteById(id);
    }
    
    @Override
    public Page<Brand> search (Brand brand, int page, int size)
    {
        QueryWrapper<Brand> brandQueryWrapper = new QueryWrapper<>();
        // 判断品牌名是否为空
        if (brand.getName() != null && StringUtils.hasText(brand.getName())) {
            brandQueryWrapper.like("name", brand.getName());
        }
        
        Page<Brand> brandPage = brandMapper.selectPage(new Page<>(page, size), brandQueryWrapper);
        
        return brandPage;
    }
}
